#include <init/GDT.h>

/* Defines a GDT entry */
struct gdt_entry
{
    _u16 limit_low;
    _u16 base_low;
    _u8 base_middle;
    _u8 access;
    _u8 granularity;
    _u8 base_high;
} __attribute__((packed));

/* Defines a GDT ponter */
struct gdt_ptr
{
    _u16 limit;
    _u32 base;
} __attribute__((packed));

/* Declaration of GDT with 3 entries.*/
struct gdt_entry gdt[3];

/* Declaration of GDT pointer */
struct gdt_ptr gdtp;

/* Implementation of this fuction is placed in init.S
   Purpose of this function is to reload new segment registers */
extern void gdt_flush();

/* Setup a descriptor in the Global Descriptor Table */
void gdt_set_gate(_s32 num, _u32 base, _u32 limit, _u8 access, _u8 granularity)
{
    /* Setup the descriptor base address */
    gdt[num].base_low    =     (base & 0xFFFF);
    gdt[num].base_middle =     (base >> 16) & 0xFF;
    gdt[num].base_high   =     (base >> 24) & 0xFF;

    /* Setup the descriptor limits */
    gdt[num].limit_low   =    (limit & 0xFFFF);
    gdt[num].granularity =    ((limit >> 16) & 0x0F);

    /* Setup the granularity and access flags */
    gdt[num].granularity |=   (granularity & 0xF0);
    gdt[num].access       =   access;
}

/* This function is called by main. This will setup the special GDT
*  pointer, set up the first 3 entries in GDT, and then
*  finally call gdt_flush() in init.S file in order
*  to tell the processor where the new GDT is and update the
*  new segment registers */
void gdt_install()
{
    /* Setup the GDT pointer and limit */
    gdtp.limit = (sizeof(struct gdt_entry) * 3) - 1;
    gdtp.base =  (_u32)&gdt;

    /* Our NULL descriptor */
    gdt_set_gate(0, 0, 0, 0, 0);

    /* The second entry is Code Segment. The base address
    *  is 0, the limit is 4GBytes, it uses 4KByte granularity,
    *  uses 32-bit opcodes, and is a Code Segment descriptor. */
    gdt_set_gate(1, 0, 0xFFFFFFFF, 0x9A, 0xCF);

    /* The third entry is Data Segment. It's exactly the
    *  same as our code segment, but the descriptor type in
    *  this entry's access byte says it's a Data Segment */
    gdt_set_gate(2, 0, 0xFFFFFFFF, 0x92, 0xCF);

    /* Flush out the old GDT and install the new changes */
    gdt_flush();
}
